#! /bin/sh

export PATH=/usr/local/bin:/usr/bin:/bin:.

cwd="`dirname $0`"
cwd="`cd $cwd;pwd;`"
cd $cwd;

usage ()
{
  echo "./exec.sh [-l \"h1 h2 h3\"] [-c \"cmd1;cmd2\"]"
  echo -e "\t-c your commands here."
  echo -e "\t-l your host_id list."
  echo -e "\t-h this help\n"
}

hostconf="/data/home/peterwang/bin/hosts.txt"

if [ ! -f $filelist ];then
  echo "I can't find filelist.txt in current directory."
  exit 1;
fi

if [ $# -lt 1 ]; then
  usage;
  exit 2;
fi

hostlist=""
cmds=""

while getopts "c:hl:" opt;
do 
  case $opt in 
    h) usage; exit 0 ;;
    l) hostlist="$OPTARG" ;;
    c) cmds="$OPTARG" ;;
  esac
done

#echo $hostlist
#echo $cmds
if [ -z "$hostlist" ] || [ -z "$cmds" ];then
  usage;
  exit 1;
fi
#exit

for ahost in $hostlist; do
  line=`grep "^$ahost:" $hostconf`
  echo "$line"|tr ':' '\011'|
  while read id user pass host port;do
    echo -ne "$id: $user@$host#$port\n";
    expect -f do_exec.exp $user $pass $host $port "$cmds"
  done
done
